#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <stdio.h>
#include <errno.h>

#define SERVER_PORT 8888
#define MAX_MSG_SIZE 1024 //服务器发送和接收数据缓冲区的大小

int main(void)
{
    int sockfd, addrlen, n;
    struct sockaddr_in addr; //定义服务器端套接口地址数据结构
    char msg[MAX_MSG_SIZE];
    sockfd = socket(AF_INET, SOCK_DGRAM, 0); //服务器端开始建立 socket 描述符
    if (sockfd < 0)
    {
        fprintf(stderr, "Socket Error: %s\n", strerror(errno));
        exit(1);
    }
    addrlen = sizeof(struct sockaddr_in);
    bzero(&addr, addrlen); //缓冲区清空
    //服务器端填充sockaddr结构
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(SERVER_PORT);
    if (bind(sockfd, (struct sockaddr *)(&addr), addrlen) < 0)
    {
        fprintf(stderr, "Bind Error:%s\n", strerror(errno));
        exit(1);
    }
    //从网络中读取数据，并打印出接收到的数据
    while (1)
    {
        bzero(msg, MAX_MSG_SIZE); //接收数据之前先将缓冲区清零
        n = recvfrom(sockfd, msg, sizeof(msg), 0, (struct sockaddr *)(&addr), &addrlen);
        fprintf(stdout, "Receive message from client: %s\n", msg);
        //从终端读入用户输入的数据，发送到网络中去
        fgets(msg, MAX_MSG_SIZE, stdin);
        printf("Server endpoint input message: %s\n", msg);
        sendto(sockfd, msg, n, 0, (struct sockaddr *)(&addr), addrlen);
    }
    close(sockfd); //通信结束，关闭通信
    exit(0);
}